package com.example.demo.smartLamp.controller;

import com.example.demo.common.ApiResponse;
import com.example.demo.smartLamp.VO.LightIdVo;
import com.example.demo.smartLamp.entity.request.PutVideoAndImgRequest;
import com.example.demo.smartLamp.entity.response.PutResponse;
import com.example.demo.smartLamp.mapper.ImageMapper;
import com.example.demo.smartLamp.mapper.VideoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin
@RequestMapping("SSEtest")
@Api(value = "SSE测试",tags = "SSE测试")
public class SSEControler {
    @Resource
    private VideoMapper videoMapper;
    @Resource
    private ImageMapper imageMapper;

    //建立之后根据订单id，将SseEmitter存到ConcurrentHashMap
    //正常应该存到数据库里面，生成数据库订单，这里我们只是模拟一下
    public static final ConcurrentHashMap<Long, SseEmitter> sseEmitters = new ConcurrentHashMap<>();

    //第2步：接受用户建立长连接，表示该用户已支付，已支付就可以生成订单(未确认状态)
    @GetMapping(path= "/orderpay",produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter orderpay() {
        Long payid = 1L;
        //设置默认的超时时间60秒，超时之后服务端主动关闭连接。
        SseEmitter emitter = new SseEmitter(60 * 1000L);
        sseEmitters.put(payid,emitter);
        emitter.onTimeout(() -> sseEmitters.remove(payid));
        return emitter;
    }

    //第3步：接受支付系统的支付结果告知，表明用户支付成功
    @GetMapping("/payback")
    public void payback (){
        //把SSE连接取出来
        SseEmitter emitter = sseEmitters.get(1L);
        try {
            //第4步：由服务端告知浏览器端：该用户支付成功了
            emitter.send("用户支付成功"); //触发前端message事件。
            //触发前端自定义的finish事件
            emitter.send(SseEmitter.event().name("finish").id("6666").data("哈哈"));
        } catch (IOException e) {
            emitter.completeWithError(e);   //出发前端onerror事件
        }
    }


    @ApiOperation(value="投放视频、图片(type:0视频，1图片)")
    @PostMapping("/putVideoAndImage")
    public void putVideoAndImage(@RequestBody PutVideoAndImgRequest putVideoAndImgRequest) throws Exception {
        int id = putVideoAndImgRequest.getId();
        int type = putVideoAndImgRequest.getType();
        PutResponse putResponse = new PutResponse();
        SseEmitter emitter = sseEmitters.get(1L);
        if (type == 0){
            String videoUrl = videoMapper.getUrl(id);
            putResponse.setUrl(videoUrl);
            putResponse.setType(0);
            emitter.send(putResponse);
        }else if (type == 1){
            String imgUrl = imageMapper.getUrl(id);
            putResponse.setUrl(imgUrl);
            putResponse.setType(1);
            emitter.send(putResponse);
        }
    }


}
